#pragma warning(disable:4996)
#include<WinSock2.h>
#include<iostream>
#include<string>
using namespace std;
#pragma comment(lib,"ws2_32.lib") //引入库 ws2_32.lib(固定用法)

uint16_t serverport = 8080;
std::string serverip = "121.37.163.198";
int main()
{
	//初始化模块，仅Windows系统需要（固定用法）
	WSADATA WSAData;
	WORD sockVersion = MAKEWORD(2, 2);
	if (WSAStartup(sockVersion, &WSAData) != 0)
		return 0;

	//建立socket
	SOCKET clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (INVALID_SOCKET == clientSocket)
	{
		cout << "socket error!";
		return 0;
	}

	//建立sockaddr
	sockaddr_in dstAddr;
	dstAddr.sin_family = AF_INET;
	dstAddr.sin_port = htons(serverport);
	dstAddr.sin_addr.S_un.S_addr = inet_addr(serverip.c_str());

	while (1)
	{
		//发消息
		std::cerr << "Please input the message that you want to send: " << std::endl;
		std::string message;
		std::getline(std::cin, message);
		sendto(clientSocket, message.c_str(), message.size(), 0, (sockaddr*)&dstAddr, sizeof(dstAddr));
		
		//收消息
		char buffer[1024];
		struct sockaddr_in temp;
		int len = sizeof(temp);
		int s = recvfrom(clientSocket, buffer, sizeof buffer, 0, (sockaddr*)&temp, &len);
		if (s > 0)
		{
			buffer[s] = 0;
			printf("Obtain message of the server: %s\n", buffer);
		}
	}

	//关闭socket(windows独有)
	closesocket(clientSocket);
	WSACleanup();

	return 0;
}
